package com.my.socket.nio.v28;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * Created by ZhongGang
 * at 2018/8/21 10:39
 */
public class Reader implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Reader.class);

    private Selector selector;
    private SocketChannel socketChannel;
    private ByteBuffer buffer = ByteBuffer.allocate(1024);

    Reader(Selector selector, SocketChannel socketChannel) throws Exception {
        this.selector = selector;
        this.socketChannel = socketChannel;
        this.socketChannel.configureBlocking(false);
    }

    @Override
    public void run() {
        try {
            this.socketChannel.read(buffer);
            String request = new String(this.buffer.array());
            LOGGER.info("read: {}", request);

            Writer writer = new Writer(this.selector, this.socketChannel, request);
            SelectionKey selectionKey = this.socketChannel.register(this.selector, SelectionKey.OP_WRITE, writer);
            LOGGER.info("register write event, selection key: {}", selectionKey);
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
        }
    }
}
